package com.situ.mall.controller;

import com.situ.mall.pojo.Shipping;
import com.situ.mall.pojo.User;
import com.situ.mall.service.IUserService;
import com.situ.mall.util.Result;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/checkUserLogin")
    @ResponseBody
    public Result checkUserLogin(HttpSession session) {
        System.out.println("UserController.checkUserLogin");
        User user = (User) session.getAttribute("user");
        return user != null ? Result.ok() : Result.error();
    }

    @RequestMapping("/login")
    @ResponseBody
    public Result login(@Param("username") String username, @Param("password") String password, HttpSession session) {
        System.out.println("UserController.login");
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user);
            return Result.ok("登录成功");
        } else {
            return Result.error("登录失败");
        }
    }

    @RequestMapping("/getLoginPage")
    public String getLoginPage(HttpSession session) {
        if (session.getAttribute("uri") == null) {
            session.setAttribute("uri", "/");
        }
        return "login";
    }

    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    @RequestMapping("/insert")
    @ResponseBody
    public Result insert(User user) {
        boolean isSuccess = userService.inset(user);
        return isSuccess ? Result.ok("注册成功") : Result.error("注册失败");
    }

    @RequestMapping("/getUserCenterPage")
    public String getUserCenterPage() {
        return "user_center_info";
    }

    @RequestMapping("/getAddressListPage")
    public String getAddressListPage(Model model, HttpSession session) {
        List<Shipping> list = userService.selectAddress((User) session.getAttribute("user"));
        model.addAttribute(("list"), list);
        return "user_center_site";
    }

    @RequestMapping("/getUserUpdatePage")
    public String getUserUpdatePage() {
        return "user_info_update";
    }

    @RequestMapping("/update")
    @ResponseBody
    public Result update(User user, HttpSession session) {
        boolean isSuccess = userService.update(user);
        if (isSuccess) {
            session.setAttribute("user", user);
            return Result.ok("修改成功");
        } else {
            return Result.error("更新失败");
        }
    }
}
